package com.harry.greendaomaster.view;

import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.harry.greendaomaster.MyApp;
import com.harry.greendaomaster.R;
import com.harry.greendaomaster.adapter.WorkAdapter;
import com.harry.greendaomaster.base.BaseActivity;
import com.harry.greendaomaster.db.Work;
import com.harry.greendaomaster.greendao.gen.DaoSession;
import com.harry.greendaomaster.greendao.gen.UserDao;
import com.harry.greendaomaster.greendao.gen.WorkDao;
import com.harry.greendaomaster.util.DealNum;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class DataActivity extends BaseActivity implements View.OnClickListener {

    private EditText mNumber, mName, mWork, updateName;
    private RecyclerView mRecycle;
    private WorkDao workDao;

    @Override
    protected void initView() {
        mNumber = findViewById(R.id.number);
        mName = findViewById(R.id.name);
        mWork = findViewById(R.id.work);
        updateName = findViewById(R.id.updateName);
        Button cleanMath = findViewById(R.id.cleanMath);
        Button mAdd = findViewById(R.id.add);
        Button mDelete = findViewById(R.id.delete);
        Button mUpdate = findViewById(R.id.update);
        Button mSelect = findViewById(R.id.select);
        Button mBtnMath = findViewById(R.id.btnMath);
        mRecycle = findViewById(R.id.recycle);
        mAdd.setOnClickListener(this);
        mDelete.setOnClickListener(this);
        mUpdate.setOnClickListener(this);
        mSelect.setOnClickListener(this);
        cleanMath.setOnClickListener(this);
        mBtnMath.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        /**
         * 初始化数据库
         */
        DaoSession daoSession = MyApp.getInstances().getDaoSession();
        workDao = daoSession.getWorkDao();
    }

    @Override
    protected int createViews() {
        return R.layout.activity_data;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add:
                insertUser();
                break;
            case R.id.delete:
                deleteUser();
                break;
            case R.id.update:
                updateUser();
                break;
            case R.id.select:
                selectUser();
                break;
            case R.id.cleanMath:
                updateMath();
                break;
            case R.id.btnMath:
                updateBtn();
                break;
        }
    }

    /**
     * 数据去重
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
   /* private void dataRemove() {
        String number = mNumber.getText().toString().trim();
        Work work = workDao.queryBuilder()
                .where(
                        WorkDao.Properties.Number.eq(number)
                ).build()
                .unique();
        if (work != null) {
            // 用户名已存在,更新用户数据
            updateMath();
        } else {
            // 用户名不存在,插入新用户
            insertUser();
        }
    }*/

    private void updateMath() {
        String hexStr = "FE08762B5600520100000300C9FE08762B5600520100000300C9";
        String hex = DealNum.substring(hexStr, 0, 26);
        Log.e("> 48", "notifyData: " + hex);
        List<Work> list = workDao.loadAll();

        /**
         * 方式一：
         */
//        for (int i = 0; i < list.size() - 1; i++) {
//            for (int j = list.size() - 1; j > i; j--) {
//                if (list.get(j).getNumber() == (list.get(i).getNumber())) {
//                    list.remove(list.get(j));
//                }
//            }
//        }

        /**
         * 方式二：
         */
//        List<Work> workList = removeDuplicateWithOrder(list);

        /**
         * 方式三
         */
        Map<String, Work> map = new HashMap<>();
        for (Work stu : list) {
            if (!map.containsKey(stu.getNumber())) {
                map.put(String.valueOf(stu.getNumber()), stu);
            }
        }
        list.clear();
        list.addAll(map.values());
        //利用Collections.sort方法按照年龄排序，默认升序
        Collections.sort(list, (a, b) -> {
            return a.getNumber() - b.getNumber();
        });

        Log.e("去重数据集合 >>", "selectUser: " + list.size());
        LinearLayoutManager manager = new LinearLayoutManager(DataActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycle.setLayoutManager(manager);
        WorkAdapter userAdapter = new WorkAdapter(this, list);
        mRecycle.setAdapter(userAdapter);
    }

    private void updateBtn() {
        String name = mName.getText().toString().trim();
        List<Work> list = workDao.queryBuilder()
                .where(
                        WorkDao.Properties.UserName.eq(name)
                ).build()
                .list();

        Map<String, Work> map = new HashMap<>();
        for (Work stu : list) {
            if (!map.containsKey(stu.getNumber())) {
                map.put(String.valueOf(stu.getNumber()), stu);
            }
        }
        list.clear();
        list.addAll(map.values());
        //利用Collections.sort方法按照年龄排序，默认升序
        Collections.sort(list, (a, b) -> {
            return a.getNumber() - b.getNumber();
        });

        Log.e("去重数据集合 >>", "selectUser: " + list.size());
        LinearLayoutManager manager = new LinearLayoutManager(DataActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycle.setLayoutManager(manager);
        WorkAdapter userAdapter = new WorkAdapter(this, list);
        mRecycle.setAdapter(userAdapter);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static List<Work> removeDuplicateWithOrder(List<Work> list) {
//        Map<String, Line> storeAttrMap = list.stream().collect(Collectors.toMap(Line::getTime, Function.identity(), (k1, k2) -> k1));
//        list = new ArrayList<>(storeAttrMap.values());
        HashSet<Work> set = new HashSet<>();
        for (Work line : list) {
            if (!set.contains(line.getNumber())) {
                set.add(line);
            }
        }
        return list;


    }

    /**
     * 添加
     */
    private void insertUser() {
        String number = mNumber.getText().toString().trim();
        int num = Integer.parseInt(number);
        String userName = mName.getText().toString().trim();
        String worker = mWork.getText().toString().trim();

        workDao.insertOrReplace(new Work(null, num, userName,worker));
    }

    /**
     * 删除
     */
    private void deleteUser() {
        String name = mName.getText().toString();

        /**
         * <条件删除>
         *      用户名 Username
         *      单个条件删除 eq
         * </条件删除>
         */
        workDao.queryBuilder()
                .where(
                        UserDao.Properties.Username.eq(name)
                ).buildDelete()
                .executeDeleteWithoutDetachingEntities();
    }

    /**
     * 修改
     */
    private void updateUser() {
        //用户名
        String name = mName.getText().toString();

        //修改后的用户名
        String updateMsg = updateName.getText().toString();

        /**
         * <条件修改>
         *      用户名 Username
         *      修改多条用户重复数据 eq
         * </条件修改>
         */
        List<Work> list = workDao.queryBuilder()
                .where(
                        WorkDao.Properties.Worker.eq(name)
                ).build()
                .list();

        Log.e("数据", "updateUser: " + list.size());
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setWorker(updateMsg);
                workDao.update(list.get(i));
            }
        }
    }

    /**
     * 查询
     */
    private void selectUser() {
        //用户名
        String name = mName.getText().toString();

        /**
         * 查询全部用户数据
         */
        List<Work> list = workDao.loadAll();

        Log.e("当前数据集合 >>", "selectUser: " + list.size());
        LinearLayoutManager manager = new LinearLayoutManager(DataActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycle.setLayoutManager(manager);
        WorkAdapter userAdapter = new WorkAdapter(this, list);
        mRecycle.setAdapter(userAdapter);
    }
}